#include <QDebug>
#include "cvhttp.h"

/*!
  Get method
 */
CVHttp::CVHttp(QUrl url) : debug(false)
{
    this->mUrl = url;
    manager = new QNetworkAccessManager();
    QNetworkRequest request(url);
    reply = manager->get(request);
    initSlots();
}

/*!
  Post method
 */
CVHttp::CVHttp(QUrl url, QByteArray bytes) : debug(false)
{
    this->mUrl = url;
    manager = new QNetworkAccessManager();

    QNetworkRequest request(url);
    int contentLength = bytes.length();
    request.setHeader(QNetworkRequest::ContentTypeHeader,"application/x-www-form-urlencoded");
    request.setHeader(QNetworkRequest::ContentLengthHeader, contentLength);
    reply = manager->post(request, bytes);
    initSlots();
}

void CVHttp::setDebug(bool debug)
{
    this->debug = debug;
}

void CVHttp::readyReadSlot()
{
    qDebug() << "ready read Start...";
    emit readyRead();
}

void CVHttp::downloadProgressSlot(qint64 bytesReceived, qint64 total)
{
    emit downloadProgress(bytesReceived, total);
}

void CVHttp::finishedSlot()
{
    if (reply->error() == QNetworkReply::NoError)
    {
        CVSession *session = CVSession::get();
        QList<QNetworkCookie> cookies = manager->cookieJar()->cookiesForUrl(this->mUrl);
        //qDebug() << "Cookies: " << cookies;
        session->setCookies(cookies);

        QTextCodec *codec = QTextCodec::codecForName("utf8");
        QString jsonStr = codec->toUnicode(reply->readAll());
        if (debug)
        {
            qDebug() << "Json string: " << jsonStr;
        }
        if (!jsonStr.isEmpty())
        {
            QScriptEngine engine;
            QScriptValue json = engine.evaluate("(" + jsonStr + ")");
            if (!json.isError()) // no error
            {
                QScriptValue status = json.property("status");
                if (status.toInt32() == 0) // data returns correctly
                {
                    emit finished(json.property("result"), "");
                }
                else
                {
                    emit finished(NULL, json.property("message").toString());
                }
                return;
            }
        }
    }

    emit handleError(QNetworkReply::UnknownContentError);

}

void CVHttp::errorSlot(QNetworkReply::NetworkError error)
{
    emit handleError(error);
}


void CVHttp::ignoreSslError(QNetworkReply *, QList<QSslError>)
{
    qDebug() << "reply ssl error, ignore it.";
    reply->ignoreSslErrors();
}

void CVHttp::initSlots()
{
    connect(reply, SIGNAL(readyRead()), this, SLOT(readyReadSlot()));
    connect(reply, SIGNAL(downloadProgress(qint64,qint64)), this, SLOT(downloadProgressSlot(qint64,qint64)));
    connect(reply, SIGNAL(finished()), this, SLOT(finishedSlot()));
    connect(reply, SIGNAL(error(QNetworkReply::NetworkError)), this, SLOT(errorSlot(QNetworkReply::NetworkError)));
    connect(manager, SIGNAL(sslErrors(QNetworkReply*,QList<QSslError>)), this, SLOT(ignoreSslError(QNetworkReply*,QList<QSslError>)));
}


